//
//  PPIndexTableViewController.m
//  pet
//
//  Created by 陈无忌 on 10/16/14.
//  Copyright (c) 2014 whalefin. All rights reserved.
//

#import "PPIndexViewController.h"
#import "PPTopicDetailViewController.h"
#import "PPUserCenterMainPageTableViewController.h"
#import "PPOtherUserCardViewController.h"
#import "PPIndexTableViewCell.h"
#import "PPCheckBoxTableViewCell.h"
#import "PPSystemConfiguraton.h"
#import "supportingHeadFiles.h"
#import "PPImageDisplayViewController.h"
#import "PPCustomBGTableView.h"

@interface PPIndexViewController ()<UIAlertViewDelegate,UITabBarControllerDelegate,UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate,UIGestureRecognizerDelegate,UISearchBarDelegate>
@property (nonatomic, strong) NSMutableArray *indexTopicArray;
@property (nonatomic, weak) PPSystemConfiguraton *config;
@property (nonatomic, strong) UIAlertView *alert;

@property (strong, nonatomic) IBOutlet PPCustomBGTableView *indexTable;
@property (weak, nonatomic) IBOutlet UIView *filtView;
@property (weak, nonatomic) IBOutlet UITableView *filtTableView;

@property (strong, nonatomic) NSArray *filtArray;
@property (strong, nonatomic) NSMutableArray *selectArray;
@property (strong, nonatomic) NSString *tagString;

@property (nonatomic, strong) UIRefreshControl *refreshControl; //下拉刷新
@property (nonatomic) BOOL isRefresh;

//search bar
@property (weak, nonatomic) IBOutlet UISearchBar *topicSearchBar;
@property (nonatomic) BOOL isSearch;

//table view scroll
@property (nonatomic) CGFloat beforeDragOffSetY;
@property (nonatomic) CGFloat didDragOffSetY;
@property (nonatomic) BOOL isScroll;

@end

@implementation PPIndexViewController

- (NSMutableArray *)indexTopicArray
{
    if (!_indexTopicArray) {
        _indexTopicArray = [NSMutableArray array];
    }
    return _indexTopicArray;
}

- (NSArray *)filtArray
{
    if (!_filtArray) {
        _filtArray = @[@"狗",@"猫",@"虫",@"鸟",@"鱼",@"两爬",@"小宠"];
    }
    return _filtArray;
}

-(PPSystemConfiguraton *)config
{
    if (!_config) {
        _config = [PPSystemConfiguraton sharedSystemConfiguration];
    }
    return  _config;
}
-(UIAlertView *)alert
{
    if (!_alert) {
        _alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"您尚未登录，请先登录！" delegate:self cancelButtonTitle:@"返回" otherButtonTitles:@"去登录", nil];
    }
    return _alert;
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"index_Title"] forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setTintColor:[UIColor grayColor]];
    [self.indexTable reloadData];
    
    self.filtView.hidden = YES;
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:YES];
    //页面消失 显示导航栏
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:nil] forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
    self.filtView.hidden = YES;
}

- (void)setTagString
{
    self.tagString = @"";
    for (int i = 0;i < self.selectArray.count;i++ ) {
        NSNumber *selectNum = [self.selectArray objectAtIndex:i];
        if ([selectNum boolValue]) {
            NSString *tag = [self.filtArray objectAtIndex:i];
            self.tagString = [self.tagString stringByAppendingString:tag];
            self.tagString = [self.tagString stringByAppendingString:@","];
        }
    }
    if (self.tagString.length > 0) {
        self.tagString = [self.tagString substringWithRange:NSMakeRange(0, self.tagString.length - 1)];
        
        self.filtView.hidden = YES;
        [self getTopic];
    }else{
        [self alertShow:@"必须选择一项"];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.indexTable.delegate = self;
    self.indexTable.dataSource = self;
    self.indexTable.frame = CGRectMake(0, 44, 320, self.view.frame.size.height - 44);
    //下拉刷新控件
    self.refreshControl = [[UIRefreshControl alloc] init];
    self.refreshControl.attributedTitle = [[NSAttributedString alloc] initWithString:@"正在刷新"];
    [self.refreshControl addTarget:self action:@selector(refreshTableView) forControlEvents:UIControlEventValueChanged];
    [self.indexTable addSubview:self.refreshControl];
    self.isRefresh = NO;
    self.isScroll = NO;

    self.selectArray = [[NSMutableArray alloc] initWithArray:@[@(1),@(1),@(1),@(1),@(1),@(1),@(1)]];
    
    self.filtTableView.delegate = self;
    self.filtTableView.dataSource = self;
    self.filtTableView.scrollEnabled = NO;
    
    [self setTagString];
    
    [self.tabBarController setDelegate:self];
    
    [self searchBarSet];
}

- (void)searchBarSet{
    self.topicSearchBar.delegate = self;
    self.topicSearchBar.placeholder = @"话题搜索";
    self.isSearch = NO;
    [self.topicSearchBar setImage:[UIImage imageNamed:@"searchIcon"] forSearchBarIcon:UISearchBarIconSearch state:UIControlStateNormal];
}

- (void)refreshTableView{
    self.isRefresh = YES;
    [self getTopic];
}


- (void)getSearchTopic
{
    [HUD showUIBlockingIndicatorWithText:@"正在搜索"];
    NSString *url = [PPAPIList getAPIList].PPQueryTopicByKeyWord;
    NSDictionary *params = @{@"keyWord":self.topicSearchBar.text};
    [httpRequst POST:url parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [self.indexTopicArray removeAllObjects];
        NSNumber *processResult = responseObject[@"processResult"];
        if (processResult.intValue == 1) {
            NSDictionary *resultMap = responseObject[@"resultMap"];
            NSArray *topicList = resultMap[@"topicList"];
            NSMutableArray *topicArray = [PPTopic arrayOfModelsFromDictionaries:topicList];
            for (PPTopic *topic in topicArray) {
                if(topic.topicImgList.count > 0)
                {
                    [self.indexTopicArray addObject:topic];
                }
            }
            //完成搜索，显示自己的群组列表
            self.isSearch = NO;
            [self.topicSearchBar resignFirstResponder];
//            self.topicSearchBar.text = @"";
            [self.topicSearchBar setShowsCancelButton:NO animated:YES];
            [self.navigationController setNavigationBarHidden:NO animated:YES];
            self.indexTable.scrollEnabled = YES;
            //数据刷新
            [self.indexTable reloadData];
        }else{
            [PPHUD hudShowWithString:@"数据获取失败!" andView:self.view];
        }
        [HUD hideUIBlockingIndicator];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [HUD hideUIBlockingIndicator];
        [PPHUD hudShowWithString:@"网络不给力!" andView:self.view];
    }];
}


- (void)getTopic
{
    if (!self.isRefresh) {
        [HUD showUIBlockingIndicatorWithText:@"正在加载"];
    }
    NSString *url = [PPAPIList getAPIList].PPQueryTopicByTag;
    NSDictionary *params = @{@"tag":self.tagString};
    [httpRequst POST:url parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [self.indexTopicArray removeAllObjects];
        [self.indexTopicArray addObject:self.config.officeTopic];
        NSNumber *processResult = responseObject[@"processResult"];
        if (processResult.intValue == 1) {
            NSDictionary *resultMap = responseObject[@"resultMap"];
            NSArray *topicList = resultMap[@"topicList"];
            NSMutableArray *topicArray = [PPTopic arrayOfModelsFromDictionaries:topicList];
            for (PPTopic *topic in topicArray) {
                if(topic.topicImgList.count > 0)
                {
                    [self.indexTopicArray addObject:topic];
                }
            }
            
            [self.indexTable reloadData];
        }else{
            [PPHUD hudShowWithString:@"数据获取失败!" andView:self.view];
        }
        if (self.isRefresh) {
            [self.refreshControl endRefreshing];
            self.isRefresh = NO;
        }
        [HUD hideUIBlockingIndicator];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [HUD hideUIBlockingIndicator];
        [PPHUD hudShowWithString:@"网络不给力!" andView:self.view];
        if (self.isRefresh) {
            [self.refreshControl endRefreshing];
            self.isRefresh = NO;
        }
    }];
}


-(void)alertShow:(NSString *)msg
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:msg delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
    [alert show];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UISearch bar delegate

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{
#pragma mark - 设置了筛选栏隐藏
    if (!self.filtView.hidden) {
        self.indexTable.scrollEnabled = YES;
        [self setTagString];
        return NO;
    }
    self.isSearch = YES;
    //开始编辑 取消按钮出现
    [searchBar setShowsCancelButton:YES animated:YES];
    self.indexTable.scrollEnabled = NO;
    return YES;
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    
    [self getSearchTopic];
    [searchBar resignFirstResponder];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    self.isSearch = NO;
    //取消搜索，显示自己的群组列表
    [searchBar resignFirstResponder];
    searchBar.text = @"";
    [searchBar setShowsCancelButton:NO animated:YES];
    self.indexTable.scrollEnabled = YES;
}

#pragma mark - UIScroll View delegate
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    self.beforeDragOffSetY = scrollView.contentOffset.y;
    self.isScroll = YES;
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    self.didDragOffSetY = scrollView.contentOffset.y;
    if (self.isScroll) {
        if (self.beforeDragOffSetY > self.didDragOffSetY) {
            //手势向下 显示顶部搜索栏 跟 search bar 隐藏LOGO
            if (self.topicSearchBar.hidden) {
                self.topicSearchBar.hidden = NO;
            }
            if (!self.navigationController.navigationBar.hidden) {
                [self.navigationController setNavigationBarHidden:YES animated:YES];
            }
            if (self.tabBarController.tabBar.hidden) {
                self.tabBarController.tabBar.hidden = NO;
                CGRect frame = CGRectMake(0, 44, 320, self.view.frame.size.height - 44);
                self.indexTable.frame = frame;
            }
        }else{
            //手势向上 隐藏底部tabbar 跟search bar 显示LOGO
            if (!self.topicSearchBar.hidden) {
                self.topicSearchBar.hidden = YES;
            }
            if (self.navigationController.navigationBar.hidden) {
                [self.navigationController setNavigationBarHidden:NO animated:YES];
            }
            if (!self.tabBarController.tabBar.hidden) {
                self.tabBarController.tabBar.hidden = YES;
                CGRect frame = CGRectMake(0, 0, 320, self.view.frame.size.height + 49);
                self.indexTable.frame = frame;
            }
        }
    }
    [NSObject cancelPreviousPerformRequestsWithTarget:self];
    [self performSelector:@selector(scrollViewDidEndScrollingAnimation:) withObject:nil afterDelay:0.1];
}

-(void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
{
    [NSObject cancelPreviousPerformRequestsWithTarget:self];
    self.isScroll = NO;
    if (self.indexTable.contentOffset.y == 0) {
        NSLog(@"scroll to top");
        //show all
        [self.navigationController setNavigationBarHidden:NO animated:YES];
        self.topicSearchBar.hidden = NO;
        self.tabBarController.tabBar.hidden = NO;
    }
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if ([tableView isEqual:self.indexTable]) {
        return self.indexTopicArray.count;
    }else{
        return self.filtArray.count;
    }
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([tableView isEqual:self.indexTable]) {
        PPTopic *topic = [self.indexTopicArray objectAtIndex:indexPath.row];
        PPTopicImage *img = topic.topicImgList.firstObject;
        PPUserInfo *user = topic.userList.firstObject;
        PPIndexTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"indexCell"];
        [cell.backGroundImageView setImageWithURL:[PPImageUrl getImageUrlOriginal:img.img] placeholderImage:[UIImage imageNamed:@"defaultImage"] usingActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        [cell.backGroundImageView setContentMode:UIViewContentModeScaleAspectFill];
        [cell.backGroundImageView setClipsToBounds:YES];
        [cell.userAvatarImageView setImageWithURL:[PPImageUrl getImageUrl:user.userAvatar] placeholderImage:[UIImage imageNamed:@"defaultAvatar"] usingActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        cell.userAvatarImageView.layer.borderWidth = 1.5;
        UIColor *borderColor = [UIColor whiteColor];
        [cell.userAvatarImageView.layer setBorderColor:borderColor.CGColor];
        
        switch (user.gender) {
            case 0:
                [cell.userNameLabel setTextColor:[UIColor colorWithRed:0/255.0 green:163/255.0 blue:228/255.0 alpha:1.0]];
                if (topic.topicLikeNum.count > 0) {
                    [cell.likeButton setImage:[UIImage imageNamed:@"blueHeart"]];
                }else{
                    [cell.likeButton setImage:[UIImage imageNamed:@"whiteHeart"]];
                }
                
                break;
            case 1:
                [cell.userNameLabel setTextColor:[UIColor colorWithRed:221/255.0 green:19/255.0 blue:123/255.0 alpha:1.0]];
                if (topic.topicLikeNum.count > 0) {
                    [cell.likeButton setImage:[UIImage imageNamed:@"redHeart"]];
                }else{
                    [cell.likeButton setImage:[UIImage imageNamed:@"whiteHeart"]];
                }
                break;
            default:
                break;
        }
        
        if (user.address.length > 0) {
            cell.userNameLabel.text = [NSString stringWithFormat:@"%@/%@",user.userName,user.address];
        }else{
            cell.userNameLabel.text = user.userName;
        }
        
        
        cell.likeCountLabel.text = [NSString stringWithFormat:@"%@",@(topic.topicLikeNum.count)];
        cell.conmentCountLabel.text = [NSString stringWithFormat:@"%@",@(topic.replyNum.count)];
        // Configure the cell...
        cell.topicContentLabel.text = topic.content;
        
        
        UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(goInfo:)];
        cell.userAvatarImageView.tag = indexPath.row;
        recognizer.numberOfTouchesRequired = 1;
        recognizer.numberOfTapsRequired = 1;
        cell.userAvatarImageView.userInteractionEnabled = YES;
        [cell.userAvatarImageView addGestureRecognizer:recognizer];

        
        return cell;

    }else{
        PPCheckBoxTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"checkBoxCell"];
        NSString *type = [self.filtArray objectAtIndex:indexPath.row];
        cell.nameLabel.text = type;
        [cell.selectButton addTarget:self action:@selector(select:) forControlEvents:UIControlEventTouchUpInside];
        NSNumber *selectStatus = [self.selectArray objectAtIndex:indexPath.row];
        if ([selectStatus boolValue]) {
            [cell.selectButton setBackgroundImage:[UIImage imageNamed:@"select"] forState:UIControlStateNormal];
        }else{
            [cell.selectButton setBackgroundImage:[UIImage imageNamed:@"disselect"] forState:UIControlStateNormal];
        }
        
        cell.selectButton.tag = indexPath.row;
        return cell;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([tableView isEqual:self.indexTable]) {
        return 175;
    }else{
        return 32;
    }
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.isSearch) {
        return;
    }
    if ([tableView isEqual:self.indexTable]) {
#pragma mark - 设置了筛选栏隐藏
        if (!self.filtView.hidden) {
            self.indexTable.scrollEnabled = YES;
            [self setTagString];
            return;
        }
        if (self.config.isLogin) {
            PPTopic *topic = [self.indexTopicArray objectAtIndex:indexPath.row];
            PPTopicDetailViewController *targetVC = [self.storyboard instantiateViewControllerWithIdentifier:@"PPTopicDetailViewController"];
            targetVC.topic = topic;
            [self.navigationController pushViewController:targetVC animated:YES];
        }else{
            [self.alert show];
        }
    }else if ([tableView isEqual:self.filtTableView]){
        NSNumber *selectStatus = [self.selectArray objectAtIndex:indexPath.row];
        if ([selectStatus boolValue]) {
            [self.selectArray replaceObjectAtIndex:indexPath.row withObject:[NSNumber numberWithBool:NO]];
            //        selectStatus = [NSNumber numberWithBool:NO];
        }else{
            [self.selectArray replaceObjectAtIndex:indexPath.row withObject:[NSNumber numberWithBool:YES]];
            //        selectStatus = [NSNumber numberWithBool:YES];
        }
        [self.filtTableView reloadData];
    }
}


#pragma mark - UIAlert View Delegate
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        [self performSegueWithIdentifier:@"goLogin" sender:self];
    }
}

#pragma mark - UITabbar Delegate
- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController
{
    if (!self.config.isLogin) {
        [self.alert show];
        return NO;
    }
    return YES;
}


#pragma mark - Custom IBAction

- (IBAction)filtViewShow:(id)sender {
    if (self.isSearch) {
        return;
    }
    if (self.filtView.hidden) {
        self.filtView.hidden = NO;
        self.indexTable.scrollEnabled = NO;
    }else{
        self.indexTable.scrollEnabled = YES;
        [self setTagString];
    }
}

- (void)select:(UIButton *)sender
{
    NSNumber *selectStatus = [self.selectArray objectAtIndex:sender.tag];
    if ([selectStatus boolValue]) {
        [self.selectArray replaceObjectAtIndex:sender.tag withObject:[NSNumber numberWithBool:NO]];
    }else{
        [self.selectArray replaceObjectAtIndex:sender.tag withObject:[NSNumber numberWithBool:YES]];
    }
    [self.filtTableView reloadData];
}

- (void)goInfo:(UITapGestureRecognizer *)sender
{
    if (self.config.isLogin) {
        if (self.isSearch) {
            return;
        }
#pragma mark - 设置了筛选栏隐藏
        if (!self.filtView.hidden) {
            self.indexTable.scrollEnabled = YES;
            [self setTagString];
            return;
        }
        UITapGestureRecognizer *tap = sender;
        UIImageView *IV= (UIImageView *)tap.view;
        PPTopic *topic = [self.indexTopicArray objectAtIndex:IV.tag];
        if (topic.userId == [PPSystemConfiguraton sharedSystemConfiguration].userInfo.id) {
            //myCenter
            PPUserCenterMainPageTableViewController *targetVC = [self.storyboard instantiateViewControllerWithIdentifier:@"PPUserCenterMainPageTableViewController"];
            [self.navigationController pushViewController:targetVC animated:YES];
        }else{
            PPOtherUserCardViewController *targetVC = [self.storyboard instantiateViewControllerWithIdentifier:@"PPOtherUserCardViewController"];
            targetVC.user = topic.userList.firstObject;
            [self.navigationController pushViewController:targetVC animated:YES];
        }
    }else{
        [self.alert show];
    }
    
    
}

@end
